import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCookie, removeAllCookies } from '@/utils/auth'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL as string | undefined,
  withCredentials: true,
  timeout: 60000
})
// 请求拦截
service.interceptors.request.use((config: AxiosRequestConfig) => {
  Object.assign(config.headers, {
    'X-Token': getCookie('token')
  })
  return config
})
interface IResponse<T = any> {
  code: number
  msg: string
  data: T
}
// 响应拦截
service.interceptors.response.use(
  (response: any) => {
    const res = response.data as IResponse
    // 无token或者token过期
    if (res.code === 20000) {
      ElMessageBox.confirm('账号异常，您可以取消停留在该页上，或重新登录', '提示', {
        type: 'error',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false
      })
        .then(() => {
          removeAllCookies()
          window.location.reload()
        })
        .catch(() => {})
    }
    if (res.code === -1) {
      ElMessage.error(res.msg)
      return Promise.reject(res.msg)
    }
    return res
  },
  (err) => {
    console.log(err)
  }
)

export default service
